<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

    <form class="" action="/lesson18" method="post">
      <input type="text" name="name" value="" placeholder="your name"/>
      <div class="" data-success style="color:green">

      </div>
      <div class="" error-data="name" style="color:red">
      </div>
      <input type="text" name="email" value="" placeholder="your email"/>
      <div class="" error-data="email" style="color:red">

      </div>
      <input type="submit" name="" value="submit">
    </form>

    <script type="text/javascript">
      const formDOM = document.querySelector("form");
      const errorName = formDOM.querySelector("[error-data=name]");
      const errorEmail = formDOM.querySelector("[error-data=email]");
      const success = formDOM.querySelector("[data-success]");
      formDOM.onsubmit = function(event){
        event.preventDefault();
        var nameInput = formDOM.querySelector("input");
        var name = nameInput.value;
        var email = nameInput.nextElementSibling.nextElementSibling.nextElementSibling.value;
        console.log(name,email);
        // var name = nameInput.value;
        // var email = emailInput.value;
        fetch("/lesson18", {
          method:"POST",
          body:JSON.stringify({name, email}),
          headers:{
            "Content-Type":"application/json"
          }
        }).then(res=>res.text())
        .then(errors=>{
          errorName.innerText="";
          errorEmail.innerText="";
          success.innerText = "";
          if (errors) {
            errors = JSON.parse(errors);
            if (errors.name) {
              errorName.innerText = errors.name;
            }
            if (errors.email) {

              errorEmail.innerText = errors.email;
            }
          }else {
            success.innerText = "successful!!!";
          }
        });
      };
    </script>
  </body>
</html>
